package com.itheima.tanhua.service;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import com.itheima.tanhua.api.db.UserInfoApi;
import com.itheima.tanhua.api.mongodb.CommentApi;
import com.itheima.tanhua.enums.CommentType;
import com.itheima.tanhua.enums.Constants;
import com.itheima.tanhua.pojo.db.UserInfo;
import com.itheima.tanhua.pojo.mongo.Comment;
import com.itheima.tanhua.vo.CommentsVo;
import com.itheima.tanhua.vo.PageResult;
import org.apache.dubbo.config.annotation.DubboReference;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class CommentService {


    @DubboReference
    private CommentApi commentApi;

    @DubboReference
    private UserInfoApi userInfoApi;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;



    /**
     * 评论列表   该动态的所有评论的展示
     * @param page
     * @param pagesize
     * @param movementId
     * @return
     */
    public PageResult commentsList(Integer page, Integer pagesize, String movementId) {

        //1.通过动态id查询所有的评论 列表 展示出来
       List<Comment> commentList= commentApi.findComments(page,pagesize,movementId,CommentType.COMMENT);
        //获取评论过此动态的userId 查询出此用户的信息
        List<Long> userIds = CollUtil.getFieldValues(commentList, "userId",Long.class);
        //获取用户的id
        Map<Long,UserInfo> map=new HashMap<>();
         int counts=0;
        for (Long userId : userIds) {
            UserInfo userInfo = userInfoApi.selectById(userId);
            map.put(userId,userInfo);
            counts++;
        }
        //封装对象
        List<CommentsVo> commentsVoList=new ArrayList<>();
        for (Comment comment : commentList) {
            CommentsVo commentsVo=new CommentsVo();
            UserInfo userInfo = map.get(comment.getUserId());
            BeanUtil.copyProperties(userInfo,commentsVo);
            BeanUtil.copyProperties(comment,commentsVo);
            commentsVo.setHasLiked(0);
            Date date = new Date(comment.getCreated());
            commentsVo.setCreateDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date));
            commentsVo.setId(comment.getId().toHexString());
            commentsVoList.add(commentsVo);
        }
        //5、构造返回值
        return new PageResult(page,pagesize,commentsVoList,01,counts);

    }


    /**
     * 发布评论
     * @param param
     */
    public void postComments(Map<String, String> param) {
        //获取param中存储的值
        String movementId = param.get("movementId");
        String content = param.get("comment");
        //获取用户的id
        Long uid = Convert.toLong(stringRedisTemplate.opsForValue().get("CHECK_ID"));

        Comment comment=new Comment();
        comment.setUserId(uid);
        comment.setPublishId(new ObjectId(movementId));
        comment.setCommentType(CommentType.COMMENT.getType());
        comment.setContent(content);
        comment.setCreated(System.currentTimeMillis());
        commentApi.saveComment(comment);
    }

    /**
     * 添加点赞
     * @param movementId
     */
    public Integer likeComment(String movementId) {
        Long uid = Convert.toLong(stringRedisTemplate.opsForValue().get("CHECK_ID"));
        //判断是否已经点赞
        boolean result = commentApi.isComment(movementId, uid, CommentType.LIKE);
        if (result) {
            //表示已经点赞过了
            throw new RuntimeException("已经点赞了");
        }
        //未点赞
        //1.通过movementId 获取发帖人的详细信息
        //2.完善用户comment的集合的数据  进行添加操作
        Comment comment = new Comment();
        comment.setPublishId(new ObjectId(movementId));
        comment.setUserId(uid);
        comment.setCommentType(CommentType.LIKE.getType());
        comment.setCreated(System.currentTimeMillis());
        //在mongodb中添加数据  并返回所有的点赞数
        Integer likeCounts = commentApi.saveComment(comment);
        //3.在redis中存储数据 hasLiked
        String redisKey = Constants.MOVEMENTS_INTERACT_KEY + movementId;
        String hashKey = Constants.MOVEMENT_LIKE_HASHKEY + uid;
        //将是否点赞保存到redis中 使用hash表
        stringRedisTemplate.opsForHash().put(redisKey, hashKey, "1");
        //返回此条动态的所有点赞数
        return likeCounts;
    }

    public Integer disLikeComment(String movementId) {
        //获取当前用户的id
        Long uid = Convert.toLong(stringRedisTemplate.opsForValue().get("CHECK_ID"));
        //判断是否已经点赞
        boolean result = commentApi.isComment(movementId, uid, CommentType.LIKE);
        if (!result) {
            //表示已经点赞过了
            throw new RuntimeException("未点赞,无法取消点赞");
        }
        //删除已经点赞的数据
        Comment comment = new Comment();
        comment.setPublishId(new ObjectId(movementId));
        comment.setUserId(uid);
        comment.setCommentType(CommentType.LIKE.getType());
        comment.setCreated(System.currentTimeMillis());
        //在mongodb中添加数据  并返回所有的点赞数
        Integer likeCounts = commentApi.deleteComment(comment);
        //从redis中删除此
        String redisKey = Constants.MOVEMENTS_INTERACT_KEY + movementId;
        String hashKey = Constants.MOVEMENT_LIKE_HASHKEY + uid;
        //将是否点赞保存到redis中 使用hash表
        stringRedisTemplate.opsForHash().delete(redisKey,hashKey);
        return likeCounts;
    }

    public Integer loveCommment(String movementId) {
        Long uid = Convert.toLong(stringRedisTemplate.opsForValue().get("CHECK_ID"));
        //判断是否已经点赞
        boolean result = commentApi.isComment(movementId, uid, CommentType.LOVE);
        if (result) {
            //表示已经点赞过了
            throw new RuntimeException("已经点赞了");
        }
        //未点赞
        //1.通过movementId 获取发帖人的详细信息
        //2.完善用户comment的集合的数据  进行添加操作
        Comment comment = new Comment();
        comment.setPublishId(new ObjectId(movementId));
        comment.setUserId(uid);
        comment.setCommentType(CommentType.LOVE.getType());
        comment.setCreated(System.currentTimeMillis());
        //在mongodb中添加数据  并返回所有的点赞数
        Integer loveCounts = commentApi.saveComment(comment);
        //3.在redis中存储数据 hasLiked
        String redisKey = Constants.MOVEMENTS_INTERACT_KEY + movementId;
        String hashKey = Constants.MOVEMENT_LOVE_HASHKEY + uid;
        //将是否点赞保存到redis中 使用hash表
        stringRedisTemplate.opsForHash().put(redisKey, hashKey, "1");
        //返回此条动态的所有点赞数
        return loveCounts;

    }

    public Integer unloveCommment(String movementId) {
        //获取当前用户的id
        Long uid = Convert.toLong(stringRedisTemplate.opsForValue().get("CHECK_ID"));
        //判断是否已经点赞
        boolean result = commentApi.isComment(movementId, uid, CommentType.LOVE);
        if (!result) {
            //
            throw new RuntimeException("未点赞,无法取消点赞");
        }
        //删除已经点赞的数据
        Comment comment = new Comment();
        comment.setPublishId(new ObjectId(movementId));
        comment.setUserId(uid);
        comment.setCommentType(CommentType.LOVE.getType());
        comment.setCreated(System.currentTimeMillis());
        //在mongodb中添加数据  并返回所有的点赞数
        Integer loveCounts = commentApi.deleteComment(comment);
        //从redis中删除此
        String redisKey = Constants.MOVEMENTS_INTERACT_KEY + movementId;
        String hashKey = Constants.MOVEMENT_LOVE_HASHKEY + uid;
        //将是否点赞保存到redis中 使用hash表
        stringRedisTemplate.opsForHash().delete(redisKey,hashKey);
        return loveCounts;
    }
}
